package com.hzdp.netty.linebase;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

import org.apache.log4j.Logger;

public class TimeServerHandler extends ChannelHandlerAdapter {

	protected static Logger logger = Logger.getLogger(TimeServerHandler.class);

	private int counter;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
		logger.info("SERVER Received -> " + body + ";counter=" + ++counter);

		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "Bad Order";
		currentTime = currentTime + System.getProperty("line.separator");
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.writeAndFlush(resp);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
